﻿using HealthcareSystem.API.Read.Application.Command.Equipment;
using HealthcareSystem.API.Read.DTO.Equipment;
using HealthcareSystem.Domain.BasicSettings.Equipment;
using MediatR;
using Microsoft.AspNetCore.Server.HttpSys;
using System.Collections.Generic;
using WeekExam.PassPort.ErrorCode;
using WeekExam.PassPort.Infrastructure.Interface;

namespace HealthcareSystem.API.Read.Application.CommandHandel.Equipment
{
    /// <summary>
    /// 设备请求查询命令
    /// </summary>
    public class EquipmentQueryCommandHandler : IRequestHandler<EquipmentQueryCommand, ApiResult<ApiPaging<List<EquipmentDTO>>>>
    {
        private readonly IBaseRepository<EquipmentTable> equipRep;

        public EquipmentQueryCommandHandler(IBaseRepository<EquipmentTable> equipRep)
        {
            this.equipRep = equipRep;
        }

        public Task<ApiResult<ApiPaging<List<EquipmentDTO>>>> Handle(EquipmentQueryCommand request, CancellationToken cancellationToken)
        {
            ApiResult<ApiPaging<List<EquipmentDTO>>> result=new ApiResult<ApiPaging<List<EquipmentDTO>>>();
            result.Code=ResultCode.查询成功;
            result.Message=ResultCode.查询成功.ToString();

            var res = from a in equipRep.GetAll()
                      where !a.IsDelete
                      select new EquipmentDTO
                      {
                          EquipmentId=a.EquipmentId,
                          EquipmentBrand=a.EquipmentBrand,
                          EquipmentName=a.EquipmentName,
                          EquipmentCoding=a.EquipmentCoding,
                          EquipmentType=a.EquipmentType,
                          EquipmentSNnum=a.EquipmentSNnum,
                          EquipmentStatus=a.EquipmentStatus,
                          IsDelete=a.IsDelete,
                          CreatedTime= a.CreatedTime
                      };
            if (!string.IsNullOrEmpty(request.EquipmentName))
            {
                res=res.Where(x=>x.EquipmentName.Contains(request.EquipmentName));
            }
            //总条数
            var totalcount = res.Count();
            //总页数
            var totalpage = (int)Math.Ceiling(request.pagindex * 1.0/request.pagsize);
            //排序
            res = res.OrderByDescending(x => x.EquipmentId).Skip((request.pagindex - 1) * request.pagsize).Take(request.pagsize);

            ApiPaging< List < EquipmentDTO >> paging =new ApiPaging<List<EquipmentDTO>>();
            paging.totalCount = totalcount;
            paging.totalPage = totalpage;
            paging.Data = res.ToList();
            result.Data = paging;
            return Task.FromResult(result);

        }
    }
}
